<template>
  <a-modal
    :title=" model!=null ? '修改简历' : '新增简历'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
		<a-form-item label="简历名称">
		  <a-input v-decorator="['name',{rules: [{required: true, min: 1, message: '请输入至少三个字符！'}]}]"  />
		</a-form-item>
		<a-form-item label="简历附件">
		   <a-upload
			  :before-upload="beforeUpload"
			  :remove="handleRemove"
			  :file-list="fileList"
			  v-decorator="['attach', {rules:[{ required: true, validator: this.handleAttachCheck }],validateTrigger: 'blur'}]"
		    >
		      <a-button> <a-icon type="upload" /> 上传简历 </a-button>
		    </a-upload>
		</a-form-item>
			<a-form-item label="描述">
				<a-input v-decorator="['desp']" />
			</a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 表单字段
const fields = ['desp', 'id', 'name', 'attach']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
	  fileList: []
    }
  },
  created () {
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
	  this.fileList = []
      this.model && this.form.setFieldsValue(pick(this.model, fields))
	  if(this.model.id){
	  	this.fileList = [
	  	  {
	  		uid: this.model.id,
	  		name: this.model.attach,
	  		status: 'done',
	  		url: 'http://localhost:8080/static/' + this.model.attach,
	  	  }
	  	]
		console.log(this.fileList)
	  }
    })
  },
  methods: {
	handleRemove(file) {
		  const index = this.fileList.indexOf(file)
		  this.fileList = this.fileList.splice(index, 1)
	},
	beforeUpload(file) {
		const isLt10M = file.size / 1024 / 1024 < 10
		  if(!isLt10M) {
			this.$message.error(file.name + '文件大小超出10M限制，请修改后重新上传')
			return false
		  } else {
			this.fileList = [file];
			return false
		  }
	},
	handleAttachCheck(rule, value, callback){
		if(this.fileList.length > 0){
			callback()
		}else{
			callback(new Error('请上传附件！'))
		}
	}
  }
}
</script>
